package com.sgcc;


import javax.imageio.ImageIO;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.awt.*;
import java.awt.image.BufferedImage;
import java.io.IOException;
import java.util.Random;

public class CheckCode extends HttpServlet {
    public void doGet(HttpServletRequest request, HttpServletResponse response)
            throws IOException {

          /*
          在内存中生成图片，设置背景颜色，花填充矩形，并且和纸的大小相同，矩形有颜色
          获取笔 的对象
          先准备好数据，随机生辰四个字符，把字符画到纸上
          画干扰线
          把内存中的图片输出到客户端上
          */
        int width=120;
        int height=30;

        BufferedImage image=new BufferedImage(width, height, BufferedImage.TYPE_INT_RGB);

        Graphics2D g=(Graphics2D) image.getGraphics();
        g.setColor(Color.GRAY);
        g.fillRect(0, 0, width, height);
        g.setColor(Color.BLUE);
        g.drawRect(0, 0, width-1, height-1);

        String words="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghjjklmnopqrstuvwxyz0123456789";

        g.setColor(Color.YELLOW);
        g.setFont(new Font("隶书",Font.BOLD,20));

        Random random=new Random();
        int x=20;
        int y=20;
        int x1,x2,y1,y2;
        for(int i=0;i<4;i++){
            //画弧度
            int jiaodu=random.nextInt(80)-40;
            double hudu=jiaodu * Math.PI /180;
            g.rotate(hudu,x,y);

            int index=random.nextInt(words.length());
            char ch=words.charAt(index);
            g.drawString(""+ch,x,y);
            g.rotate(-hudu,x,y);
            x +=20;
            //画干扰线
            x1=random.nextInt(width);
            y1=random.nextInt(height);
            x2=random.nextInt(width);
            y2=random.nextInt(height);
            g.drawLine(x1, y1, x2, y2);
        }
        ImageIO.write(image, "jpg", response.getOutputStream());
        System.out.println("调用成功");

    }
    public void doPost(HttpServletRequest request, HttpServletResponse response)
            throws IOException {
        doGet(request, response);
    }

}
